import logging
import time
from dataclasses import dataclass
from hashlib import md5
from typing import Optional

import mysql.connector
from mysql.connector import pooling
from dotenv import load_dotenv
import os
from gloal.config import sendInfo, getEnv

# 加载.env文件
load_dotenv()

host = os.getenv('MYSQL_HOST')
user = os.getenv('MYSQL_USER')
password = os.getenv('MYSQL_PASSWORD')
db = os.getenv('MYSQL_DB')

# 创建一个连接池
dbconfig = {
    "host": host,
    "user": user,
    "password": password,
    "database": db
}
pool = pooling.MySQLConnectionPool(pool_name="my_pool", pool_size=10, **dbconfig)

logging.basicConfig(filename='../logs/baidu.log',
                    level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s')

conn = pool.get_connection()
cursor = conn.cursor()


@dataclass
class BaiduData:
    Title: str
    Source: str
    Summary: str
    SendTime: str
    link: str
    linkMd5: str
    imgUrl: str
    keywords: str
    addTime: float
    Id: Optional[int] = None
    # def __init__(self, Id, Title, Source, Summary, SendTime, link, imgUrl, keywords, addTime):
    #     self.Id = Id
    #     self.Title = Title
    #     self.Source = Source
    #     self.Summary = Summary
    #     self.SendTime = SendTime
    #     self.link = link
    #     self.imgUrl = imgUrl
    #     self.linkMd5 = hashlib.md5(link.encode()).hexdigest()
    #     self.keywords = keywords
    #     self.addTime = addTime

    @staticmethod
    def getList():
        sql = "SELECT * FROM baidu order by addTime desc"
        cursor.execute(sql)
        result = cursor.fetchall()
        return result

    def getLinkMd5(self):
        return md5(self.link.encode()).hexdigest()

    def getListByLinkMd5(self):
        linkmd5 = self.getLinkMd5()
        sql = "SELECT * FROM baidu WHERE linkMd5 = %s"
        cursor.execute(sql, (linkmd5,))
        result = cursor.fetchall()
        return result

    def save(self):
        # 插入数据的 SQL 查询
        insert_query = "INSERT INTO baidu (" \
                       "Title, " \
                       "`Source`, " \
                       "Summary, " \
                       "SendTime, " \
                       "link, " \
                       "imgUrl," \
                       "linkMd5," \
                       "keywords," \
                       "addTime" \
                       ") VALUES (" \
                       "%s, %s, %s, %s, %s, %s, %s, %s, %s)"

        # 数据
        data_to_insert = (
            self.Title,
            self.Source,
            self.Summary,
            self.SendTime,
            self.link,
            self.imgUrl,
            self.linkMd5,
            self.keywords,
            time.time()
        )

        # 使用连接池获取连接并执行查询
        try:
            conn = pool.get_connection()
            cursor = conn.cursor()

            # 执行插入查询
            cursor.execute(insert_query, data_to_insert)
            # 提交更改
            conn.commit()

        except mysql.connector.Error as err:
            logging.error("Error: {}".format(err))
            text = "【Baidu - Mysql异常报警】"
            text += "Mysql-Error: {}".format(err)
            sendInfo(text)

        finally:
            # 释放资源
            if 'conn' in locals():
                conn.close()
